<?php

namespace app\process;

use app\model\Device;
use app\service\AlarmService;
use support\Log;
use Workerman\Crontab\Crontab;

class Task
{
    public function onWorkerStart()
    {
        // 每5秒执行一次
        new Crontab('*/60 * * * * *', function () {
            // echo date('Y-m-d H:i:s') . "\n";

            $devices =  Device::query()->where('alarm', '>', 0)->get();

            foreach ($devices as $device) {

                try {

                    Log::info('enter listener');
                    // 获取更新的设备ID
                    $deviceId = $device->id;

                    // 检查alarm字段是否更新且大于0
                    if ($device && $device->alarm > 0) {
                        // 处理报警
                        $alarmService = new AlarmService();
                        $alarmService->handleDeviceAlarm($deviceId);
                    }
                } catch (\Exception $e) {
                    error_log("Device alarm listener error: " . $e->getMessage());
                }
            }
        });
    }
}
